package org.activemonitoring.datastore.rest;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.activemonitoring.domain.Measures;
import org.apache.commons.lang.exception.ExceptionUtils;

@Provider
@Consumes("text/xml")
public class MeasuresReader implements MessageBodyReader<Measures> {

    private JAXBContext context;

    public MeasuresReader() throws JAXBException {
        super();
        this.context = createJaxbContext();
    }

    protected JAXBContext createJaxbContext() throws JAXBException {
        return JAXBContext.newInstance(Measures.class);
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type.equals(Measures.class) && mediaType.equals(MediaType.TEXT_XML_TYPE);
    }

    @Override
    public Measures readFrom(Class<Measures> type, Type genericType, Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException,
            WebApplicationException {
        try {
            return (Measures) this.context.createUnmarshaller().unmarshal(entityStream);
        } catch (JAXBException e) {
            Throwable t = ExceptionUtils.getRootCause(e);
            throw new IOException(t);
        }
    }
}
